package tsing.good_simple.goodutil;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2024/7/17 16:25
 * @Author Tsing
 * 读取EXCEL文件的工具类
 */
public class ExcelUtil {


    /**
     * 读取EXCEL的通用泛型方法
     * @param clazz
     * @param path
     * @param paramNames
     * @return
     * @param <T>
     * @throws Exception
     */
    public static <T> List<T> poiReadExcelMethod(Class<T> clazz,String path,String... paramNames ) throws Exception {
        List<T> ts = new ArrayList<>();
        // 读Excel文件
        File file = new File(path);
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(file);
            Sheet sheetAt = wb.getSheetAt(0);
            for (int i = 1; i < 500; i++) {
                Row row = sheetAt.getRow(i);
                if (row != null) {
                    T t = clazz.getDeclaredConstructor().newInstance();
                    for (String paramName : paramNames) {
                        Field field = clazz.getDeclaredField(paramName);
                        field.setAccessible(true);
                        // 构建set方法的名称
                        String methodName = "set" + paramName.substring(0, 1).toUpperCase() + paramName.substring(1);
                        // 获取set方法
                        Method setter = clazz.getMethod(methodName, field.getType());
                        Cell cell = row.getCell(0);
                        // 调用set方法
                        setter.invoke(t, cell.getStringCellValue());
                    }
                    ts.add(t);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }



    /**
     * 读Excel文件
     * @param list
     */
    public static void poiReadExcelMethod(List<String> list,String path) {
        File file = new File(path);
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(file);
            Sheet sheetAt = wb.getSheetAt(0);
            for (int i = 1; i < 500; i++) {
                Row row = sheetAt.getRow(i);
                if (row != null) {
                    Cell cell = row.getCell(0); //计费类型
                    list.add(cell.getStringCellValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
    }



}
